import cv2
import json
import numpy as np
'''
Created on Nov 5, 2012

@author: x220
'''

    
class differencesDetector:
    def __init__(self,background,debug=False,thresholdValue=50,contourSize=1000,number_of_iterations=1,kernelNr=1,gray=True):
        self.debug=debug
        self.thresholdValue=thresholdValue
        self.oldframe = None
        self.controurSize = contourSize
        if(gray):
            background = cv2.cvtColor(background,cv2.COLOR_RGB2GRAY)
        self.background = background
        self.number_of_iterations = number_of_iterations
        self.kernel = np.ones((kernelNr,kernelNr),'uint8')
        self.gray =gray
        if(self.debug):
            cv2.namedWindow('edge')
            cv2.createTrackbar('thresholdValue', 'edge', 0, 255, self._callbak)
            cv2.createTrackbar('controurSize', 'edge', 0, 9000, self._callbak)
            cv2.createTrackbar('number_of_iterations', 'edge', 1, 19, self._callbak)
            cv2.createTrackbar('kernelNr', 'edge', 1, 19, self._callbak)
    
    
    def _callbak(self,*arg):
        self.thresholdValue = cv2.getTrackbarPos('thresholdValue', 'edge')
        self.controurSize = cv2.getTrackbarPos('controurSize', 'edge')
        self.number_of_iterations = cv2.getTrackbarPos('number_of_iterations', 'edge')
        kernelNr = cv2.getTrackbarPos('kernelNr', 'edge')
        self.kernel = np.ones((kernelNr,kernelNr),'uint8')
        self.proces(self.oldframe)
    
    def proces(self, frame): 
        self.oldframe = frame  
        if(self.gray):
            frame = cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY)
            
        frame_differences= cv2.absdiff(self.background, frame)     
        frame_threshold = cv2.threshold(frame_differences, self.thresholdValue, 255, cv2.THRESH_BINARY)[1]
        frame_dilate = cv2.dilate(frame_threshold, self.kernel,iterations=self.number_of_iterations)
        finalFrame = cv2.erode(frame_dilate,self.kernel,iterations=self.number_of_iterations)
        if not self.gray:
            finalFrame = cv2.cvtColor(finalFrame,cv2.COLOR_RGB2GRAY)
            
        contours, temp = cv2.findContours(finalFrame,cv2.RETR_LIST  ,cv2.CHAIN_APPROX_NONE)
        
        if(self.debug):
            cv2.imshow('edge',finalFrame)
        contoursWithCorrectSize = []  
        if(len(contours) != 0):
            for contour in contours:
                if(cv2.contourArea(contour)>self.controurSize):
                        for cordinate in contour:
                            contoursWithCorrectSize.append(int(cordinate[0][0]))
                            contoursWithCorrectSize.append(int(cordinate[0][1]))
        return contoursWithCorrectSize
    
    def getJsonString(self,data):
        return str(json.dumps(data))
        
        
    def show(self,contours,frame=None):
        if frame==None:
            frame = np.empty(frame.shape)
        for i in range(0,len(contours),2):
            cord = (contours[i],contours[i+1])
            cv2.line(frame, cord, cord,(0,0,255),2)
        cv2.imshow("contours", frame)